<template>
  <div>
    <el-select
      v-model="currentValue"
      :multiple="multiple"
      :disabled="disabled"
      clearable
      filterable
      remote
      placeholder="请选择组织"
      :remote-method="remoteMethod"
      :loading="loading"
      @change="change"
    >
      <el-option v-if="showAll" :key="showAll" :label="'全部'" :value="undefined"></el-option>
      <el-option v-for="item in optionList" :key="item.id" :label="item.displayName" :value="item.id">
        <span v-if="item.level > 0" :style="{'margin-left':(item.level-1) * 40+'px'}">╰───</span>
        {{ item.displayName }}
      </el-option>
    </el-select>
  </div>
</template>

<script>
import { getOrganizationUnitsWithLevel } from "@/api/organization-unit";

export default {
  name: "OrganizationUnitSelector",
  props: {
    showAll: {
      // 为搜索设置“全部”选项
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Number, Array],
      default: undefined
    }
  },
  data() {
    return {
      currentValue: this.value,
      items: [],
      optionList: [],
      loading: false
    };
  },
  watch: {
    value(newValue) {
      this.currentValue = newValue;
    }
  },
  mounted() {
    this.load();
  },
  methods: {
    updateValue(newValue) {
      this.$emit("input", newValue);
    },

    change(val) {
      this.updateValue(val);
    },

    load() {
      this.getList();
    },
    remoteMethod(query) {
      if (query) {
        this.optionList = this.items.filter(item => {
          return item.displayName.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this.optionList = this.items;
      }
    },
    getList() {
      this.loading = true;
      getOrganizationUnitsWithLevel().then(result => {
        this.items = result;
        // this.items.forEach(item => {
        //   item.displayName = Array(item.level + 2).join("╰───") + " " + item.displayName;
        // });
        this.optionList = this.items;
        this.loading = false;
      });
    }
  }
};
</script>
